package com.ldw.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ldw.common.Constans;
import com.ldw.common.ErrorCode;
import com.ldw.mapper.RegisterMapper;
import com.ldw.mapper.SysUserMapper;
import com.ldw.pojo.SysUser;
import com.ldw.service.RegisterService;
import com.ldw.service.SysUserService;
import com.ldw.utils.JWTUtils;
import com.ldw.vo.RegisterParams;
import com.ldw.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private SysUserService SysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result register(RegisterParams params) {
        /*
         * 1.判断参数，是否合法
         * 2.判断账户是否存在，存在，返回账户已经被注册
         * 3.不存在， 注册用户
         * 4.生成token
         * 5.存入redis 并返回
         * 6.注意加上事务
         * */
        String account = params.getAccount();
        String nickname = params.getNickname();
        String password = params.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(nickname) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = SysUserService.queryUserByAccount(account);
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUT_EXIST.getCode(), ErrorCode.ACCOUT_EXIST.getMsg());
        }
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + Constans.salt));
        sysUser.setAdmin(1);
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setDeleted(0);
        sysUser.setEmail("");
        sysUser.setStatus("");
        sysUser.setSalt(Constans.salt);
        registerMapper.insert(sysUser);
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
